package com.example.utils;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidDataSourceFactory;

import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

public class JdbcUtils {
    private static DruidDataSource dataSource;
    private static ThreadLocal<Connection> conns=new ThreadLocal<Connection>();


    static {
        try {
            Properties properties=new Properties();
            //读取jdbc.properties属性配置文件
            InputStream resourceAsStream = JdbcUtils.class.getClassLoader().getResourceAsStream("jdbc.properties");
            //重流中加载数据
            properties.load(resourceAsStream);
            //创建数据库连接池
            dataSource= (DruidDataSource) DruidDataSourceFactory.createDataSource(properties);

//            System.out.println(dataSource.getConnection());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }



    /**
     * 获取数据库池 池中的连接
     * 如果返回null获取连接失败
     */
    public static Connection getConnection(){
        Connection conn=conns.get();

        if(conn==null){
            try {
                conn=dataSource.getConnection();  //数据库连接池去
                conns.set(conn);  //保存到ThreadLocal对象中，供后面的JDBC操作使用
                conn.setAutoCommit(false); //设置手动管理

            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return conn;
    }

    /**
     * 关闭连接，放回数据库连接池
     * @param conn
     */
    public static void close(Connection conn){
        if(conn!=null){
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 提交事务，并关闭连接
     */
    public static void commitAndClose(){
        Connection connection=conns.get();

        if(connection!=null){
            try {
                connection.commit();
            } catch (SQLException e) {
                e.printStackTrace();
            }finally {
                try {
                    connection.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }

            }
        }
        conns.remove();
    }
    /**
     * 回滚事务，并关闭连接
     */
    public static void rollbackAndClose(){
        Connection connection=conns.get();

        if(connection!=null){
            try {
                connection.rollback();
            } catch (SQLException e) {
                e.printStackTrace();
            }finally {
                try {
                    connection.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }

            }
        }
        conns.remove();
    }
}
